// 报表统计页面专用JavaScript

// 初始化页面
function initReportStatistics() {
    initReportTypeToggle();
    initReportActions();
    initHistoryActions();
    initTableInteractions();
    initMiniCharts();
    addEventListeners();
}

// 初始化报表类型切换
function initReportTypeToggle() {
    const reportTypeSelect = document.getElementById('reportType');
    const customDateGroup = document.querySelector('.custom-date');
    
    if (reportTypeSelect && customDateGroup) {
        reportTypeSelect.addEventListener('change', function() {
            if (this.value === 'custom') {
                customDateGroup.style.display = 'flex';
            } else {
                customDateGroup.style.display = 'none';
            }
        });
    }
}

// 初始化报表操作按钮
function initReportActions() {
    const generateReportBtn = document.querySelector('.generate-report-btn');
    const exportReportBtn = document.querySelector('.export-report-btn');
    const emailReportBtn = document.querySelector('.email-report-btn');
    
    if (generateReportBtn) {
        generateReportBtn.addEventListener('click', generateReport);
    }
    
    if (exportReportBtn) {
        exportReportBtn.addEventListener('click', exportReport);
    }
    
    if (emailReportBtn) {
        emailReportBtn.addEventListener('click', emailReport);
    }
}

// 初始化历史记录操作按钮
function initHistoryActions() {
    const downloadBtns = document.querySelectorAll('.download-btn');
    const deleteBtns = document.querySelectorAll('.delete-btn');
    const clearHistoryBtn = document.querySelector('.clear-history');
    
    downloadBtns.forEach(btn => {
        btn.addEventListener('click', downloadReport);
    });
    
    deleteBtns.forEach(btn => {
        btn.addEventListener('click', deleteReport);
    });
    
    if (clearHistoryBtn) {
        clearHistoryBtn.addEventListener('click', clearHistory);
    }
}

// 初始化表格交互
function initTableInteractions() {
    const viewDetailsBtns = document.querySelectorAll('.view-details');
    const exportTableBtns = document.querySelectorAll('.export-table');
    
    viewDetailsBtns.forEach(btn => {
        btn.addEventListener('click', viewReportDetails);
    });
    
    exportTableBtns.forEach(btn => {
        btn.addEventListener('click', exportTableData);
    });
}

// 初始化迷你图表
function initMiniCharts() {
    const miniCharts = document.querySelectorAll('.mini-chart');
    
    miniCharts.forEach((chart, index) => {
        // 根据索引设置不同的高度和颜色
        const heights = [70, 65, 75];
        const colors = ['#409eff', '#67c23a', '#e6a23c'];
        
        chart.style.backgroundColor = `rgba(${hexToRgb(colors[index])}, 0.1)`;
        
        // 创建随机的图表线条
        createMiniChartLine(chart, colors[index], heights[index]);
    });
}

// 创建迷你图表线条
function createMiniChartLine(container, color, heightPercent) {
    const canvas = document.createElement('canvas');
    canvas.width = 80;
    canvas.height = 60;
    container.appendChild(canvas);
    
    const ctx = canvas.getContext('2d');
    const data = [];
    
    // 生成随机数据
    for (let i = 0; i < 10; i++) {
        data.push(Math.random() * 0.8 + 0.2); // 0.2 到 1 之间的随机值
    }
    
    // 绘制图表
    ctx.strokeStyle = color;
    ctx.lineWidth = 2;
    ctx.beginPath();
    
    data.forEach((value, index) => {
        const x = index * (canvas.width / (data.length - 1));
        const y = canvas.height - (value * canvas.height * (heightPercent / 100));
        
        if (index === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    });
    
    ctx.stroke();
    
    // 绘制区域填充
    ctx.lineTo(canvas.width, canvas.height);
    ctx.lineTo(0, canvas.height);
    ctx.closePath();
    ctx.fillStyle = `${color}33`; // 50% 透明度
    ctx.fill();
}

// 十六进制颜色转RGB
function hexToRgb(hex) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}` : '0, 0, 0';
}

// 生成报表
function generateReport() {
    const reportType = document.getElementById('reportType').value;
    const reportContent = document.getElementById('reportContent').value;
    let dateRange = '';
    
    if (reportType === 'custom') {
        const startDate = document.getElementById('reportStartDate').value;
        const endDate = document.getElementById('reportEndDate').value;
        
        if (!startDate || !endDate) {
            showToast('请选择自定义日期范围');
            return;
        }
        
        dateRange = `${startDate} 至 ${endDate}`;
    } else {
        const typeLabels = {
            'daily': '今日',
            'weekly': '本周',
            'monthly': '本月',
            'quarterly': '本季度',
            'yearly': '本年'
        };
        dateRange = typeLabels[reportType];
    }
    
    showLoading('正在生成报表...');
    
    // 模拟API请求延迟
    setTimeout(() => {
        hideLoading();
        showToast(`报表生成成功：${dateRange} ${getContentTypeLabel(reportContent)}`);
        
        // 更新报表周期标签
        const reportPeriods = document.querySelectorAll('.report-period');
        reportPeriods.forEach(period => {
            period.textContent = dateRange;
        });
    }, 1500);
}

// 导出报表
function exportReport() {
    showLoading('正在导出报表...');
    
    // 模拟导出延迟
    setTimeout(() => {
        hideLoading();
        showToast('报表导出成功');
        
        // 记录导出历史
        addExportHistory('报表_导出');
    }, 2000);
}

// 发送邮件
function emailReport() {
    const email = prompt('请输入接收邮件地址：');
    
    if (!email) return;
    
    // 简单的邮件格式验证
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        showToast('请输入有效的邮件地址');
        return;
    }
    
    showLoading('正在发送邮件...');
    
    // 模拟发送延迟
    setTimeout(() => {
        hideLoading();
        showToast(`报表已发送至 ${email}`);
    }, 2500);
}

// 查看报表详情
function viewReportDetails(e) {
    const reportCard = e.target.closest('.report-card');
    const reportTitle = reportCard.querySelector('h3').textContent;
    
    showToast(`查看${reportTitle}详情`);
    
    // 可以在这里实现跳转到详情页面或展开详情面板
}

// 导出表格数据
function exportTableData(e) {
    const reportCard = e.target.closest('.report-card');
    const reportTitle = reportCard.querySelector('h3').textContent;
    
    showLoading('正在导出表格数据...');
    
    setTimeout(() => {
        hideLoading();
        showToast(`${reportTitle}表格数据导出成功`);
        
        // 记录导出历史
        addExportHistory(`${reportTitle}_表格`);
    }, 1500);
}

// 下载历史报表
function downloadReport(e) {
    const historyItem = e.target.closest('.history-item');
    const fileName = historyItem.querySelector('.history-name').textContent;
    
    showLoading('正在下载报表...');
    
    setTimeout(() => {
        hideLoading();
        showToast(`报表 ${fileName} 下载成功`);
    }, 1500);
}

// 删除历史报表
function deleteReport(e) {
    if (confirm('确定要删除此报表记录吗？')) {
        const historyItem = e.target.closest('.history-item');
        historyItem.style.opacity = '0';
        historyItem.style.height = '0';
        historyItem.style.marginBottom = '0';
        historyItem.style.padding = '0';
        historyItem.style.overflow = 'hidden';
        historyItem.style.transition = 'all 0.3s ease';
        
        setTimeout(() => {
            historyItem.remove();
            showToast('报表记录已删除');
        }, 300);
    }
}

// 清空历史记录
function clearHistory() {
    if (confirm('确定要清空所有报表历史记录吗？')) {
        const historyList = document.querySelector('.history-list');
        const historyItems = historyList.querySelectorAll('.history-item');
        
        historyItems.forEach((item, index) => {
            setTimeout(() => {
                item.style.opacity = '0';
                item.style.height = '0';
                item.style.marginBottom = '0';
                item.style.padding = '0';
                item.style.overflow = 'hidden';
                item.style.transition = 'all 0.3s ease';
                
                setTimeout(() => {
                    item.remove();
                    if (index === historyItems.length - 1) {
                        // 所有项都删除后显示空状态
                        const emptyState = document.createElement('div');
                        emptyState.className = 'empty-state';
                        emptyState.innerHTML = `
                            <i class="fas fa-file-alt" style="font-size: 48px; color: #ccc; margin-bottom: 16px;"></i>
                            <p style="color: #999; text-align: center;">暂无报表历史记录</p>
                        `;
                        historyList.appendChild(emptyState);
                        showToast('所有报表历史已清空');
                    }
                }, 300);
            }, index * 100);
        });
    }
}

// 添加导出历史
function addExportHistory(fileName) {
    const historyList = document.querySelector('.history-list');
    const emptyState = historyList.querySelector('.empty-state');
    
    // 移除空状态
    if (emptyState) {
        emptyState.remove();
    }
    
    // 创建新的历史记录项
    const now = new Date();
    const dateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
    const size = `${(Math.random() * 5 + 1).toFixed(1)}MB`;
    
    const historyItem = document.createElement('div');
    historyItem.className = 'history-item';
    historyItem.innerHTML = `
        <div class="history-info">
            <div class="history-name">${fileName}_${String(now.getTime()).slice(-6)}</div>
            <div class="history-meta">
                <span class="history-date">${dateStr}</span>
                <span class="history-size">${size}</span>
            </div>
        </div>
        <div class="history-actions">
            <button class="download-btn">
                <i class="fas fa-download"></i>
            </button>
            <button class="delete-btn">
                <i class="fas fa-trash"></i>
            </button>
        </div>
    `;
    
    // 添加到列表开头
    historyList.insertBefore(historyItem, historyList.firstChild);
    
    // 添加动画效果
    historyItem.style.opacity = '0';
    historyItem.style.transform = 'translateY(-10px)';
    historyItem.style.transition = 'all 0.3s ease';
    
    setTimeout(() => {
        historyItem.style.opacity = '1';
        historyItem.style.transform = 'translateY(0)';
    }, 10);
    
    // 为新添加的按钮绑定事件
    const downloadBtn = historyItem.querySelector('.download-btn');
    const deleteBtn = historyItem.querySelector('.delete-btn');
    
    downloadBtn.addEventListener('click', downloadReport);
    deleteBtn.addEventListener('click', deleteReport);
}

// 获取内容类型标签
function getContentTypeLabel(contentType) {
    const labels = {
        'all': '全部内容报表',
        'seats': '座位使用情况报表',
        'bookings': '预约统计报表',
        'users': '用户行为报表',
        'system': '系统运行报表'
    };
    
    return labels[contentType] || '报表';
}

// 显示加载动画
function showLoading(text = '加载中...') {
    const loadingOverlay = document.querySelector('.loading-overlay');
    const loadingText = loadingOverlay.querySelector('p');
    
    if (loadingText) {
        loadingText.textContent = text;
    }
    
    loadingOverlay.style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

// 隐藏加载动画
function hideLoading() {
    const loadingOverlay = document.querySelector('.loading-overlay');
    loadingOverlay.style.display = 'none';
    document.body.style.overflow = '';
}

// 显示提示框
function showToast(message, type = 'success') {
    const toast = document.querySelector('.toast');
    toast.textContent = message;
    toast.className = 'toast';
    
    // 设置不同类型的提示框样式
    switch (type) {
        case 'success':
            toast.classList.add('toast-success');
            break;
        case 'error':
            toast.classList.add('toast-error');
            break;
        case 'warning':
            toast.classList.add('toast-warning');
            break;
        case 'info':
        default:
            toast.classList.add('toast-info');
    }
    
    toast.style.display = 'block';
    
    // 3秒后自动隐藏
    setTimeout(() => {
        toast.style.display = 'none';
    }, 3000);
}

// 添加事件监听器
function addEventListeners() {
    // 报表内容选择变化
    const reportContentSelect = document.getElementById('reportContent');
    if (reportContentSelect) {
        reportContentSelect.addEventListener('change', function() {
            showToast(`已切换至${getContentTypeLabel(this.value)}`);
        });
    }
    
    // 表格行点击效果
    const tableRows = document.querySelectorAll('.report-table tbody tr');
    tableRows.forEach(row => {
        row.addEventListener('click', function() {
            showToast(`查看详情：${this.cells[0].textContent}`);
        });
    });
    
    // 键盘快捷键
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + G 生成报表
        if ((e.ctrlKey || e.metaKey) && e.key === 'g') {
            e.preventDefault();
            generateReport();
        }
        
        // Ctrl/Cmd + E 导出报表
        if ((e.ctrlKey || e.metaKey) && e.key === 'e') {
            e.preventDefault();
            exportReport();
        }
    });
    
    // 窗口大小变化时重新绘制迷你图表
    window.addEventListener('resize', function() {
        const miniCharts = document.querySelectorAll('.mini-chart');
        miniCharts.forEach(chart => {
            // 清空现有内容
            while (chart.firstChild) {
                chart.removeChild(chart.firstChild);
            }
            // 重新创建图表
            createMiniChartLine(chart, '#409eff', 70);
        });
    });
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', function() {
    initReportStatistics();
});